$(function () {
    //  按钮生成器
    generateButton($('#north'));
    generateTreeButton($('#tree_north'))
    let columns = [[
        {field: 'id', title: '主键', align: 'center', halign: 'center', sortable: true, hidden: true},
        {
            field: 'emCode', width: 100, title: '编号', align: 'center', halign: 'center', sortable: true, editor: {
                type: 'textbox', options: {required: true}
            }
        },
        {
            field: 'emName', width: 100, title: '员工名称', align: 'center', halign: 'center', sortable: true, editor: {
                type: 'textbox', options: {required: true}
            }
        },
        {
            field: 'departmentId',
            width: 100,
            title: '所属部门',
            align: 'center',
            halign: 'center',
            sortable: true,
            editor: {
                type: 'combotree',
                options: {
                    required: true,
                    url: 'jcDepartment/tree',
                    method: 'GET',
                    textField: 'text',
                    valueField: 'id',
                    panelHeight: 200,
                    onBeforeSelect: function (node) {
                        return $(this).tree('getParent', node.target) != null;
                    },
                }
            },
            formatter: (v, r, i) => {
                if (!v) return '';
                let prefix = 'jc_employee_department';
                if (sessionStorage.getItem(prefix + `_` + v) == undefined) {
                    let name = ($.ajax({
                        url: `jcDepartment/queryByPk/${v}`,
                        async: false,
                        dataType: 'json',
                        type: 'GET'
                    }).responseJSON || {})['dname'];
                    sessionStorage.setItem(prefix + `_` + v, name || '');
                }
                return sessionStorage.getItem(prefix + `_` + v);
            }
        },
        {
            field: 'remarks',
            width: 100,
            title: '备注',
            align: 'center',
            halign: 'center',
            sortable: true,
            editor: {
                type: 'textbox', options: {}
            }
        },
        {
            field: 'emState', width: 100, title: '状态', align: 'center', halign: 'center', sortable: true, editor: {
                type: 'combobox', options: {
                    data: [{id: 0, text: '停用'}, {id: 1, text: '正常'}],
                    value: 1,
                    panelHeight: 'auto',
                    textField: 'text',
                    valueField: 'id',
                    editable: false,
                    required: true
                }
            },
            formatter: (v, r, i) => {
                return v == 1 ? '正常' : '停用';
            }
        },
    ]]
    setDatagridColumnOpts($('body').data('menu_id'), $('#e_grid'), columns, edatagrid);
    etree();
    bindEnterEvents();
})
let treeEditDialogState = undefined;

function edatagrid(columns) {
    $('#e_grid').edatagrid({
        url: 'jcEmployee/queryByFk',
        saveUrl: 'jcEmployee/insertSelective',
        updateUrl: 'jcEmployee/updateSelective',
        destroyUrl: 'jcEmployee/deleteByPk',
        idField: 'id',
        destroyMsg: {
            norecord: {	// when no record is selected
                title: '警告',
                msg: '未选中任何数据'
            },
            confirm: {	// when select a row
                title: '确认',
                msg: '确定删除吗?删除后不可恢复!'
            }
        },
        loadFilter: pageFilter,
        pagination: true,
        // pagePosition: 'top',
        pageSize: 200,
        pageNumber: 1,
        pageList: [200, 400, 600, 800, 1000],
        method: 'GET',
        param: {},
        striped: true,
        fit: true,
        sortable: true,
        rownumbers: true,
        remoteSort: false,
        showFooter: true,
        singleSelect: true,
        columns: columns,
        onAdd: function (index, row) {
            //  赋值
        },
        onLoadError: function () {
            $('.easyui-linkbutton').each(function () {
                if ($(this).linkbutton('options').text == '查询') {
                    $(this).linkbutton('enable');
                }
            })
        },
        onLoadSuccess: function () {
            $(this).datagrid('enableFilter');
            $(this).data('edatagrid').options.editIndex = -1;
            $('.easyui-linkbutton').each(function () {
                if ($(this).linkbutton('options').text == '查询') {
                    $(this).linkbutton('enable');
                }
            })
        },
        onBeforeLoad: function (param) {
            $(this).datagrid('destroyFilter');
            $('.easyui-linkbutton').each(function () {
                if ($(this).linkbutton('options').text == '查询') {
                    $(this).linkbutton('disable');
                }
            })
            return true;
        },
        onSuccess: function (index, row) {
            let treeSelected = $('#e_tree').tree('getSelected');
            if (treeSelected.id != row.departmentId) {
                $('#e_tree').tree('select', $('#e_tree').tree('find', row.departmentId).target);
            } else {
                $(this).edatagrid('reload');
            }
            if (row.success) {
                $.messager.show({title: '提示', msg: row.message});
            } else {
                $(this).edatagrid('enableEditing');
                $.messager.alert('提示', row.message, 'warning')
            }
        },
        onDestroy: function (index, row) {
            $(this).edatagrid('reload');
            if (row.success) {
                $.messager.show({title: '提示', msg: row.message});
            } else {
                $.messager.alert('提示', row.message, 'warning')
            }
        },
        onError: function (index, row) {
            $.messager.show({title: '提示', msg: row.message});
        },
        onResizeColumn: function (f, w) {
            columnResizeEvent($('body').data('menu_id'), f, w);
        },
    });
}

function etree() {
    $('#e_tree').tree({
        url: 'jcDepartment/tree',
        method: 'GET',
        animate: true,
        lines: true,
        queryParams: {parentId: null},
        formatter: function (node) {
            return `${node.attribute['dCode'] || ''} ${node.text}`;
        },
        onSelect: function (node) {
            if ($(this).tree('getParent', node.target) != null) {
                $('#e_grid').datagrid('options').url = 'jcEmployee/queryByFk';
                $('#e_grid').datagrid('options').queryParams = {id: node.id};
                $('#e_grid').edatagrid('reload');
            } else {
                $('#e_grid').datagrid('options').url = 'jcEmployee/listQuery';
                $('#e_grid').datagrid('options').queryParams = {};
                $('#e_grid').edatagrid('reload');
            }
        },
        onLoadSuccess: function (node, data) {
            if (data.length > 0) {
                let id = data[0]['id'];
                let rootNode = $(this).tree('find', id);
                $(this).tree('select', rootNode.target);
            }
        }
    })
}

function btn_search() {
    let select = $('#e_tree').tree('getSelected');
    if (select != null) {
        $('#e_grid').edatagrid('reload');
    }
}

function btn_add() {
    $('#e_grid').edatagrid('addRow');
}

function btn_modify() {
    let selected = $('#e_grid').edatagrid('getSelected');
    if (selected != undefined) {
        let index = $('#e_grid').edatagrid('getRowIndex', selected);
        if (index != -1) {
            $('#e_grid').edatagrid('editRow', index);
        }
    } else {
        $.messager.alert('提示', '点击鼠标左键选中行后再执行本功能', 'warning');
    }
}

function btn_delete() {
    let selected = $('#e_grid').edatagrid('getSelected');
    if (selected != undefined) {
        let index = $('#e_grid').edatagrid('getRowIndex', selected);
        if (index != -1) {
            $('#e_grid').edatagrid('destroyRow', index);
        }
    } else {
        $.messager.alert('提示', '点击鼠标左键选中行后再执行本功能', 'warning');
    }
}

//  导入
function btn_import() {

}

function btn_save() {
    $('#e_grid').edatagrid('saveRow');
}

//  导出
function btn_export() {
    exportExcel('#e_grid', '部门员工');
}

//  树操作按钮
function btn_tree_add() {
    treeEditDialogState = 1;
    let select = $('#e_tree').tree('getSelected');
    $('#e_tree_dialog').dialog('open');
    if (select != null) {
        $('#t_form').form('clear');
        $('#t_form').form('load', {
            parentId: select.id,
            dState: 1,
        })
    }
}

function btn_tree_edit() {
    treeEditDialogState = 0;
    let select = $('#e_tree').tree('getSelected');
    if (select != null) {
        $('#e_tree_dialog').dialog('open');
        let parentNode = $('#e_tree').tree('getParent', select.target);
        $('#t_form').form('clear');
        $('#t_form').form('load', {
            id: select.id,
            parentId: parentNode ? parentNode.id : null,
            dName: select.text,
            dCode: select.attribute['dCode'],
            dState: 1,
            dDefault: select.attribute.dDefault
        });
    } else {
        $.messager.alert('提示', '请选中', 'error');
    }
}

function btn_tree_delete() {
    let select = $('#e_tree').tree('getSelected');
    if (select == null) {
        $.messager.alert('提示', '请选中', 'error');
        return;
    }
    $.messager.confirm('提示', '是否删除？', function (r) {
        if (r) {
            $.ajax({
                url: 'jcDepartment/deleteByPk',
                data: {id: select.id},
                type: 'POST',
                dataType: 'json',
                success: function (data) {
                    if (data.success) {
                        $('#e_tree').tree('reload');
                    }
                    $.messager.show({
                        title: '提示',
                        msg: data.message
                    })
                }
            })
        }
    })
}

//  模态编辑框取消按钮
function e_tree_dialog_cancel() {
    $('#e_tree_dialog').dialog('close');
}

//  模态编辑框保存按钮
function e_tree_dialog_save() {
    let url = treeEditDialogState == 1 ? 'jcDepartment/insertSelective' : 'jcDepartment/updateSelective';
    $('#t_form').form('submit', {
        url: url,
        onSubmit: function (param) {
            return $(this).form('validate');
        },
        success: function (data) {
            data = eval('(' + data + ')');
            if (data.success) {
                $('#e_tree_dialog').dialog('close');
                treeEditDialogState = undefined;
                let selected = $('#e_tree').tree('getSelected') || {};
                $('#e_tree').tree('options').onLoadSuccess = function (node, data) {
                    let selectedNode = $(this).tree('find', selected['id'] || '');
                    if (selectedNode != undefined)
                        $(this).tree('select', selectedNode.target);
                };
                $('#e_tree').tree('reload');
            }
            $.messager.show({
                title: '提示',
                msg: data.message
            })
        }
    })
}